//
//  WFInformationVC.m
//  谷居
//
//  Created by dllo on 16/6/25.
//  Copyright © 2016年 刘万方. All rights reserved.
//

#define TABLECONTENTSET (_mainTableView.contentOffset.y + 20)
#import "WFInformationVC.h"
#import "WFInformationCell.h"
#import "AFNetworking.h"
#import "NetWorkingTool.h"
#import "WFInformationModel.h"
#import "WFProjectStateModel.h"
#import "WFSpaceModel.h"
#import "WFInformationSpaceModel.h"
#import "Masonry.h"
#import "WFInformationImgModel.h"
#import "WFInformationDescriptionCell.h"

#import "MBProgressHUD.h"

#import "UMSocial.h"
#import "Masonry.h"
@interface WFInformationVC ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, WFInformationBaseTitleViewDelegate, UMSocialUIDelegate>
//@property (nonatomic, retain)

@property (nonatomic, retain) UIView *baseView;
@property (nonatomic, retain) WFInformationModel *informationModel;

@property (nonatomic, retain) NSMutableArray *taskEndSpaceArray;

@property (nonatomic, retain) NSDictionary *projectStateDic;
@end

@implementation WFInformationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
#pragma mark - 创建网络请求的线程.
    [self createDispatch];

    
    
}

/** 创建线程. */
- (void)createDispatch {
#pragma mark - 创建一个菊花页面
    [self createRoationView];
    dispatch_queue_t myQueue = dispatch_queue_create("craete", DISPATCH_QUEUE_CONCURRENT);
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_async(myQueue, ^{
        [self createData];
        dispatch_async(mainQueue, ^{

            
        });
    });
}

/** 创建进入的界面. */
- (void)createRoationView {
    _baseView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height)];
    [self.view addSubview:_baseView];
    [_baseView release];
    _baseView.backgroundColor = [UIColor whiteColor];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:_baseView animated:YES];
    hud.mode = MBProgressHUDAnimationFade;
    hud.labelText = @"刷新中";
    
    
}

#pragma mark - 创建数据
/** 创建网络请求. */
- (void)createData {
    [NetWorkingTool netWorkingWithURL:self.URL block:^(id result) {
        
        NSLog(@"url:%@", self.URL);
        [self.informationModel setValuesForKeysWithDictionary:result];
        self.taskEndSpaceArray = [WFInformationSpaceModel baseModelByArray:((NSDictionary *)self.informationModel.taskEnd)[@"space"]];
        
        self.projectStateDic = ((NSDictionary *)self.informationModel.taskEnd)[@"projectState"];
        
    
#pragma mark - 移除baseView
        [MBProgressHUD hideHUDForView:_baseView animated:YES];
        [_baseView removeFromSuperview];
        
#pragma mark - 创建mainTableView
        [self createTableViewWithObject:self.informationModel];
        
#pragma mark - 创建titleView
        [self createNavigationView];
    }];
}


/** 创建titleView. */
- (void)createNavigationView {
    WFImageView *leftNavigationBarButton = [[WFImageView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    leftNavigationBarButton.image = [UIImage imageNamed:@"返回2.png"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftNavigationBarButton];;
    UITapGestureRecognizer *tapLeft = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(popToRoot:)];
    leftNavigationBarButton.userInteractionEnabled = YES;
    [leftNavigationBarButton addGestureRecognizer:tapLeft];
    
    
    WFImageView *rightNavigationBarButton = [[WFImageView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    rightNavigationBarButton.image = [UIImage imageNamed:@"分享蓝.png"];
    UITapGestureRecognizer *rightTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sharedTo:)];
    rightNavigationBarButton.userInteractionEnabled = YES;
    [rightNavigationBarButton addGestureRecognizer:rightTap];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightNavigationBarButton];
    
    /** 创建底层uiview. */
    _navigationView = [[WFUIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    [self.view addSubview:_navigationView];
    [_navigationView release];
    _navigationView.alpha = 0;
    /** 创建左侧按钮. */
    _leftBackButton = [WFButtonImage buttonWithType:UIButtonTypeCustom];
    _leftBackButton.frame = CGRectMake(16, 26, 32, 32);
    [_leftBackButton setBackgroundImage:[UIImage imageNamed:@"返回.png"] forState:UIControlStateNormal];
    /** button 添加点击方法. */
    [_leftBackButton addTarget:self action:@selector(leftBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    /** 创建右侧按钮. */
    _rightShareButton = [WFButtonImage buttonWithType:UIButtonTypeCustom];
    _rightShareButton.frame = CGRectMake(327, 26, 32, 32);
    [self.view addSubview:_rightShareButton];
    [self.view addSubview:_leftBackButton];
    [_rightShareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.view).offset(-16);
        make.top.equalTo(self.view).offset(26);
        make.size.mas_equalTo(CGSizeMake(32, 32));
    }];
    [_rightShareButton addTarget:self action:@selector(rightBarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_rightShareButton setBackgroundImage:[UIImage imageNamed:@"分享黑.png"] forState:UIControlStateNormal];

}
/** 点击pop. */
- (void)popToRoot:(UITapGestureRecognizer *)tap {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

/** 分享按钮. */
- (void)sharedTo:(UITapGestureRecognizer *)tap {
    [UMSocialData defaultData].extConfig.title = @"分享的title";
    [UMSocialData defaultData].extConfig.qqData.url = @"http://baidu.com";
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"576d2cf7e0f55af20f003abf"
                                      shareText:@"友盟社会化分享让您快速实现分享等社会化功能，http://umeng.com/social"
                                     shareImage:[UIImage imageNamed:@"头像.png"]
                                shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToSina,UMShareToQQ,UMShareToQzone]
                                       delegate:self];

    NSLog(@"点击分享按钮");
}
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}

/** 创建tableView的方法. */
- (void)createTableViewWithObject:(id)obj {
    _mainTableView = [[WFTableView alloc] initWithFrame:CGRectMake(0, -20, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:_mainTableView];
    [_mainTableView release];
    
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    
    [_mainTableView registerClass:[WFInformationCell class] forCellReuseIdentifier:@"information"];
    [_mainTableView registerClass:[WFInformationDescriptionCell class] forCellReuseIdentifier:@"descrip"];
#pragma mark - 创建tableView 的头部视图
    _titleBaseView = [[WFInformationBaseTitleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 400)];
    _mainTableView.tableHeaderView = _titleBaseView;
    [_titleBaseView release];
    _titleBaseView.backgroundColor = [UIColor lightGrayColor];
    [_titleBaseView createTitleViewWithModel:self.informationModel];
    _titleBaseView.delegate = self;
}
#pragma mark - title的协议方法, push到下一界面
- (void)makePush {
    NSLog(@"push到下一接麦俊");
    
}

#pragma mark - tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        WFInformationSpaceModel *spaceModel =  self.taskEndSpaceArray[section - 1];
        return spaceModel.img.count;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.taskEndSpaceArray.count + 1;
}
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//    return @"title";
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        WFInformationDescriptionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"descrip" forIndexPath:indexPath];
        cell.label.text = self.projectStateDic[@"description"];
        return cell;
    } else {
        /** 先取出ima数据. */
        WFInformationSpaceModel *spaceModel = self.taskEndSpaceArray[indexPath.section - 1];
        /** 将imgModel存入一个数组. */
        
        NSMutableArray *imgArray = [WFInformationImgModel baseModelByArray:spaceModel.img];
        WFInformationImgModel *imgModel = imgArray[indexPath.row];

        WFInformationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"information" forIndexPath:indexPath];
        cell.imgModel = imgModel;

        cell.contentView.backgroundColor = [UIColor lightGrayColor];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        label.text = @"简介";
        label.textAlignment = 1;
        label.backgroundColor = [UIColor lightGrayColor];
        return label;
        
    } else {
        UIView *sectionView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)]autorelease];;
        sectionView.backgroundColor = [UIColor lightGrayColor];
        UIImageView *leftImageView = [[UIImageView alloc] init];
        [sectionView addSubview:leftImageView];
        [leftImageView release];
        [leftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(sectionView);
            make.bottom.equalTo(sectionView);
            make.top.equalTo(sectionView);
            make.width.mas_equalTo(40);
            
            //        make.size.mas_equalTo(CGSizeMake(30, 30));
        }];
        leftImageView.image = [UIImage imageNamed:@"竖线.png"];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        [sectionView addSubview:titleLabel];
        [titleLabel release];
        [titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(leftImageView.mas_right).offset(15);
            make.centerY.equalTo(sectionView);
            make.size.mas_equalTo(CGSizeMake(60, 20));
        }];
        
        WFInformationSpaceModel *spaceModel =  self.taskEndSpaceArray[section - 1];
        
        titleLabel.text =spaceModel.name;
        return sectionView;


    }
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil];
        CGRect rect = [self.projectStateDic[@"description"] boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        return rect.size.height;
    } else {
        /** 先取出ima数据. */
        WFInformationSpaceModel *spaceModel = self.taskEndSpaceArray[indexPath.section - 1];
        /** 将imgModel存入一个数组. */
        
        NSMutableArray *imgArray = [WFInformationImgModel baseModelByArray:spaceModel.img];
        WFInformationImgModel *imgModel = imgArray[indexPath.row];
        
        
        /** 取出img. */
        
        CGFloat h = (SCREEN_WIDTH - 10) * ((CGFloat)imgModel.height / (CGFloat)imgModel.width);
        NSLog(@"height: %f", h);
        return h;

    }
    
    
}
#pragma mark - scrollView的协议方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    /** 当偏移量大于0小于150的时候, 调整navigationView的透明度. 当偏移量到达150 的时候, 调整navigationController可见.*/
//    _navigationView.alpha = TABLECONTENTSET / 150;
    if (TABLECONTENTSET / 150 > 0 && TABLECONTENTSET / 150 < 1) {
        self.navigationController.navigationBarHidden = YES;

        _navigationView.alpha = TABLECONTENTSET / 150;
        _leftBackButton.hidden = NO;
        _rightShareButton.hidden = NO;
        _mainTableView.frame = CGRectMake(0, -20, _mainTableView.frame.size.width, _mainTableView.frame.size.height);

    } else if (TABLECONTENTSET / 150 >= 1) {
        _navigationView.alpha = 0;
        [_leftBackButton setHidden:YES];
        [_rightShareButton setHidden:YES];
        self.navigationController.navigationBarHidden = NO;
        _mainTableView.frame = CGRectMake(0, 0, _mainTableView.frame.size.width, _mainTableView.frame.size.height);
        self.navigationItem.hidesBackButton = YES;
    }
}

#pragma mark - 在视图将要出现的时候隐藏navigationBar
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;

}

- (void)leftBarButtonAction:(UIButton *)button {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)rightBarButtonAction:(UIButton *)button {
    NSLog(@"分享到微博按钮. ");
}


#pragma mark - 懒加载
- (WFInformationModel *)informationModel {
    if (!_informationModel) {
        _informationModel = [[WFInformationModel alloc] init];
    }
    return _informationModel;
}

- (NSMutableArray *)taskEndSpaceArray {
    if (_taskEndSpaceArray == nil) {
        _taskEndSpaceArray = [[NSMutableArray array] retain];
    }
    return _taskEndSpaceArray;
}


- (void)viewWillDisappear:(BOOL)animated {
    self.navigationController.navigationBarHidden = NO;
}
- (void)dealloc {
    [_taskEndSpaceArray release];
    [_informationModel release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
